var Util = require("../../utils/utils")

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 图片
    imageURL: "../../../../images/a.jfif",
    // 搜索记录，展示最近的 10 条
    searchRecords: [],
    // 搜索关键字
    keyword: "",
    // 搜索题目列表
    showList: [],
    // 全部题目
    allList: [],
    // 分类展示状态位 -1 未找到 0 历史搜索 1 搜索结果
    status: 0
  },

  // 前往详情页
  goQuestionShow(data) {
    // console.log(data.currentTarget.dataset);
    // 跳转详情页
    var url = `../questionShow/index?id=${data.currentTarget.dataset.id}`;
    wx.navigateTo({
      url,
      success: function (res) {
        // console.log(res);
        // console.log("跳转成功");
      },
      fail(err) {
        // console.log(err)
      }
    })
  },

  // 清除
  searchClear() {
    this.setData({
      showList: [],
      status: 0
    })
  },

  // 点击搜索记录
  searchClick(data) {
    // console.log(data.currentTarget.dataset);
    let {
      keyword
    } = data.currentTarget.dataset;
    // 回显输入框
    this.setData({
      keyword
    })
    // 搜索
    this.search({
      detail: keyword
    });
  },

  // 搜索
  search(data) {
    const keyword = data.detail;
    this.getAndFilterList(keyword);
    if (keyword != null && keyword != "") {
      // 将数据加入到 searchRecords 中
      let searchRecords = wx.getStorageSync('searchRecords');
      if (searchRecords == null || searchRecords == "") {
        searchRecords = [];
      }
      // console.log(searchRecords);
      searchRecords.push(keyword);
      wx.setStorage({
        data: searchRecords,
        key: 'searchRecords',
      })
      // 获取实时 searchRecords
      this.getAndSliceSearchRecords();
    }
  },

  // 拉取文章并按关键字过滤
  getAndFilterList(keyword) {
    if (keyword == "") {
      this.setData({
        showList: [],
        status: 0
      })
      return;
    }
    // 拉取文章列表
    var that = this;
    var url = `${app.globalData.baseURL}/api/question/question/list?page=1&limit=1000`;
    wx.request({
      url,
      success(res) {
        // console.log(res.data.page.list);
        var allList = res.data.page.list;
        allList = allList.map(e => {
          e.createTime = Util.formatTime(new Date(e.createTime));
          e.updateTime = Util.formatTime(new Date(e.updateTime));
          return e;
        })
        /** 
         * 根据关键字过滤 
         * 搜索标题/副标题是否匹配
         * */
        // var pgx = `/${that.data.keyword}/i`;
        var pgx = new RegExp(keyword, "i");
        // console.log(pgx)
        var showList = [];
        allList.map(e => {
          var mTitle = e.title + "";
          var mSubTitle = e.subTitle + "";
          if (mTitle.search(pgx) > -1 || mSubTitle.search(pgx) > -1) {
            showList.push(e);
          }
        });

        // console.log(showList);

        let status = 0;
        if (showList.length > 0) {
          status = 1;
        } else {
          status = -1;
        }

        that.setData({
          allList,
          showList,
          status
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 加载 searchRecords
    this.getAndSliceSearchRecords();
    // 拉取文章并过滤
    this.getAndFilterList("");
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 设置自定义tabbar，active显示属性
  onShow() {
    // console.log("onShow")
    // console.log("主页tab");
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        active: 1
      })
    }
  },

  // 获取至多最近 7 条数据展示
  getAndSliceSearchRecords() {
    let searchRecords;
    try {
      searchRecords = wx.getStorageSync('searchRecords') || [];
    } catch (error) {
      // console.log(error);
    }
    if (searchRecords.length > 0) {
      let begin = searchRecords.length - 7 >= 0 ? searchRecords.length - 7 : 0;
      searchRecords = searchRecords.slice(begin);
      searchRecords.reverse();
      // console.log(searchRecords);
    }
    this.setData({
      searchRecords
    });
  }

})